<template>
    <div class="ship-popup-main">
        <el-drawer v-model="show" title="发货" direction="rtl" size="45%">
            <div class="goods-table">
                <el-table
                    ref="multipleTableRef"
                    :data="Data.orderGoodsInfo.goods"
                    stripe
                    :header-cell-style="{ background: '#F9F9F9' }"
                    @selection-change="handleSelectionChange"
                    style="width: 100%">
                    <el-table-column type="selection" :selectable="checkSelectable">
                        <!-- <template #default="scope"> {{ scope.row }} </template> -->
                    </el-table-column>
                    <el-table-column label="商品信息">
                        <template #default="scope">
                            <div class="goods-item">
                                <img :src="scope.row.goodsImg" alt="" />
                                <div
                                    class="goods-item-info"
                                    :class="{ 'goods-item-info-active': scope.row.goodsStatus == 1 }">
                                    <div class="goods-item-name">
                                        {{ scope.row.goodsName }}
                                        <div v-if="scope.row.syncErp" class="sign-erp">ERP</div>
                                    </div>
                                    <div class="goods-item-sku" v-for="(el, idx) in scope.row.skuExtInfo" :key="idx">
                                        {{ el.keyAttributeName }}：{{ el.attributeValue }}
                                    </div>
                                    <div class="goods-item-price">
                                        <div v-if="props.orderType === 6">
                                            <span v-if="scope.row.sellPrice"
                                                >{{ floatDivide(scope.row.sellPrice, 100) }}元+</span
                                            >
                                            <span> {{ floatDivide(scope.row.goodPoints, 100) }}积分</span>
                                        </div>
                                        <div v-else>￥{{ floatDivide(scope.row.goodsPrice, 100) }}</div>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="buyNum" label="总数量" width="100">
                        <template #default="{ row }">
                            {{ row.buyNum }}
                            <div class="refund-status" v-if="row.refundGoodsCount - row.refundGoodsComplateCount > 0">
                                <div class="status-item">售后中</div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="buyNum" label="待发货" width="100">
                        <template #default="{ row }">
                            <!-- 待发货的sku数量=该sku初始数量-【售后完成】的商品-已发货的sku数量 -->
                            {{ row.buyNum - row.refundGoodsComplateCount - row.sendNum }}
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-if="show">
                <el-form inline ref="ruleFormRef" :model="Data" :rules="rules" @submit.prevent>
                    <el-form-item label="发货方式" prop="logisticsType" style="width: 300px">
                        <el-select v-model="Data.logisticsType" clearable placeholder="请选择发货方式">
                            <el-option
                                v-for="item in shipMethodList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="物流公司" prop="logisticsCode" style="width: 300px">
                        <el-select
                            v-model="Data.logisticsCode"
                            filterable
                            reserve-keyword
                            clearable
                            placeholder="请选择快递公司（可搜索）">
                            <el-option
                                v-for="item in Data.logisticsListFilter"
                                :key="item.id"
                                :label="item.name"
                                :value="item.code" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="快递单号" prop="logisticsNo" style="width: 300px">
                        <el-input
                            v-model="Data.logisticsNo"
                            placeholder="请录入快递单号"
                            class="setting-input"
                            maxlength="20"
                            show-word-limit
                            clearable>
                        </el-input>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="show = false">返回</el-button>
                    <el-button type="primary" @click="clickSubmit">确定</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>
<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { packSelectObjUtil, floatDivide } from '@/commons/utils';
import { ZwMessage } from '@/commons';
import constants from '@/commons/constants';
import request from '@/request';
import storage from '@/commons/storage';

const emit = defineEmits(['update:modelValue', 'getOrderList']);

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    goodsInfo: {
        type: Object,
        default: () => {}
    },
    orderId: {
        type: [String, Number],
        default: ''
    },
    orderType: {
        type: Number,
        default: 1
    }
});

const show = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        multipleTableRef.value.clearSelection();
        Data.logisticsType = '';
        Data.logisticsCode = '';
        Data.logisticsNo = '';
        emit('update:modelValue', val);
    }
});

watch(
    () => props.modelValue,
    val => {
        if (val) {
            orderDelivered();
        }
    }
);

const multipleTableRef = ref(null);

const ruleFormRef = ref(null);

const rules = reactive({
    logisticsType: [{ required: true, message: '请选择发货方式', trigger: 'change' }],
    logisticsCode: [{ required: true, message: '请选择物流公司', trigger: 'change' }],
    logisticsNo: [{ required: true, message: '请录入快递单号', trigger: 'blur' }]
});

const shipMethodList = reactive(packSelectObjUtil(constants.SHIP_METHOD_STATUS));

const Data = reactive({
    logisticsType: '',
    logisticsCompany: '',
    logisticsCode: '',
    logisticsNo: '',
    list: [],
    logisticsList: [],
    logisticsListFilter: [],
    goodsSelection: [],
    orderGoodsInfo: {}
});

const getLogisticsList = async () => {
    let res = await request('getLogisticsListServ');
    Data.logisticsList = res.data || [];
    Data.logisticsListFilter = res.data || [];
};
getLogisticsList();

const orderDelivered = async () => {
    let params = {
        orderId: props.orderId,
        shopId: storage.get('ZW-SHOPID')
    };
    let res = await request('orderDeliveredServ', params);
    Data.orderGoodsInfo = res.data || {};
};

const handleSelectionChange = val => {
    Data.goodsSelection = val;
};

const checkSelectable = row => {
    //  已发货商品不能发货、存在售后中的sku不能发货、商品全部售后的不能发货、待发货数量为0不能发货
    //  ERP的商品不支持勾选发货
    return !(
        row.goodsStatus == '1' ||
        row.refundGoodsCount - row.refundGoodsComplateCount > 0 ||
        row.buyNum == row.refundGoodsComplateCount ||
        row.buyNum - row.refundGoodsComplateCount - row.sendNum == 0 ||
        row.syncErp
    );
};

const clickSubmit = () => {
    if (!Data.goodsSelection.length) {
        ZwMessage.error('请选择商品');
        return;
    }
    let logisticsCompany = Data.logisticsList.find(el => el.code == Data.logisticsCode) || {};
    let goodsInfo = [];
    Data.goodsSelection.map(el => {
        goodsInfo.push({
            goodsId: el.goodsId,
            orderGoodsId: el.id,
            skuId: el.skuId,
            goodsCount: el.buyNum - el.refundGoodsComplateCount - el.sendNum
        });
    });

    let params = {
        orderId: props.orderId,
        logisticsType: Data.logisticsType,
        logisticsNo: Data.logisticsNo,
        logisticsCompany: logisticsCompany.name,
        logisticsCode: Data.logisticsCode,
        goodsInfo: goodsInfo
    };
    // console.log(params);

    ruleFormRef.value.validate(rule => {
        rule &&
            request('orderLogisticsServ', params).then(res => {
                ZwMessage.success('发货成功');
                show.value = false;
                emit('getOrderList');
            });
    });
};
</script>
<style lang="scss" scoped>
.ship-popup-main {
    .goods-table {
        margin-bottom: 16px;
    }
    .goods-item {
        display: flex;
        font-size: 14px;
        line-height: 14px;
        img {
            margin-right: 8px;
            width: 100px;
            height: 100px;
        }
        .goods-item-info {
            flex: 1;
            .goods-item-name {
                padding-bottom: 9px;
                color: #33302d;
            }
            .sign-erp {
                width: 40px;
                height: 20px;
                margin-left: 3px;
                background: #fffaf9;
                // padding: 0 2px;
                border-radius: 2px;
                border: 1px solid #facaa8;
                font-size: 12px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #ff6b00;
                line-height: 20px;
                display: inline-block;
                text-align: center;
            }
            .goods-item-sku {
                padding-bottom: 4px;
                color: #969696;
            }
            .goods-item-price {
                padding-top: 7px;
                color: #fa6a0a;
                display: flex;
                justify-content: space-between;
            }
        }
        .goods-item-info-active {
            background: url('@/assets/imgs/mall/order/icon_02.png') no-repeat;
            background-size: 100px 88px;
            background-position: 112px 5px;
        }
    }
    .refund-status {
        display: flex;
        flex-direction: column-reverse;
        text-align: center;
        .status-item {
            padding: 5px 16px;
            border-radius: 2px;
            border: 1px solid #eaeaea;
            width: 80px;
        }
    }
}
</style>
